﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Qcy.Jshj.Web.Helpers
{
    public enum Language
    {
        cn, en
    }

    public class LanguageHelper
    {
        /// <summary>
        /// 设置语言
        /// </summary>
        /// <param name="language"></param>
        public static void SetLanguage(Language language)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("Qcy.Jsl");
            if (cookie != null)
                cookie.Value = language.ToString();
            else
                cookie = new HttpCookie("Qcy.Jsl", language.ToString());
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 获取需要展示的语言
        /// </summary>
        /// <returns></returns>
        public static Language GetLanguage()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("Qcy.Jsl");
            if (cookie == null)
            {
                var language = GetBrowerLanguage();
                cookie = new HttpCookie("Qcy.Jsl", language.ToString());
            }
            return (Language)Enum.Parse(typeof(Language), cookie.Value);
        }

        /// <summary>
        /// 获取浏览器的语言(仅支持中文和英文)
        /// </summary>
        /// <returns></returns>
        private static Language GetBrowerLanguage()
        {
            var language = Language.cn;
            var userLanguage = HttpContext.Current.Request.UserLanguages[0];
            if (!userLanguage.ToLower().Contains("cn"))
                language = Language.en;
            return language;
        }
    }
}